package net.cn_su.sharpeyes.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import net.cn_su.sharpeyes.R;
import net.cn_su.sharpeyes.adapter.TvDangerPresenter;
import net.cn_su.sharpeyes.application.SuApplication;
import net.cn_su.sharpeyes.baseadapter.AdapterCallback;
import net.cn_su.sharpeyes.beans.DangerInfo;
import net.cn_su.sharpeyes.beans.RatedInfo;
import net.cn_su.sharpeyes.dialog.BaseDialog;
import net.cn_su.sharpeyes.pref.ServerInfo_;
import net.cn_su.sharpeyes.utils.DateTool;
import net.cn_su.sharpeyes.utils.UIUtil;
import net.cn_su.sharpeyes.utils.http.HttpClient;
import net.cn_su.sharpeyes.utils.http.HttpUrl;
import net.cn_su.sharpeyes.view.bridge.RecyclerViewBridge;
import net.cn_su.sharpeyes.view.leanback.adapter.GeneralAdapter;
import net.cn_su.sharpeyes.view.leanback.mode.ListRowPresenter;
import net.cn_su.sharpeyes.view.leanback.mode.OpenPresenter;
import net.cn_su.sharpeyes.view.leanback.recycle.RecyclerViewTV;
import net.cn_su.sharpeyes.view.other.MainUpView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 报警历史列表
 */
@EActivity(R.layout.activity_call_list)
@Fullscreen
public class CallPliceActivity extends AppCompatActivity implements AdapterCallback, RecyclerViewTV.OnItemListener {


    /*  @ViewById(R.id.refresh)
      protected HorizontalRefreshLayout mRefreshLayout;*/
    @ViewById(R.id.recycler_view)
    protected RecyclerViewTV mRecyclerView;
    @ViewById(R.id.textView_count)
    protected TextView textView_count;
    @ViewById
    protected LinearLayout btn_back;
    @ViewById(R.id.mainUpView1)
    protected MainUpView mMainUpView;

    private RecyclerViewBridge mRecyclerViewBridge;
    private View oldView;
    @ViewById
    protected ProgressBar progressBar;
    /**
     * 上拉加载是否完成
     */
    private boolean isLoadMoreFinish = true;

    private int p = 0;
    /**
     * 每页的条数
     */
    private final String COUNT = "20";


    private GeneralAdapter mAdapter;


    @App
    protected SuApplication suApplication;

    @Pref
    protected ServerInfo_ serverInfo;

    @AfterViews
    protected void initData() {
        btn_back.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mMainUpView.setVisibility(View.GONE);
                } else {
                    mMainUpView.setVisibility(View.VISIBLE);
                }
            }
        });
        mMainUpView.setEffectBridge(new RecyclerViewBridge());
        // mMainUpView.setDrawUpRectPadding(new Rect(0, 0, 0, 0));
        // 注意这里，需要使用 RecyclerViewBridge 的移动边框 Bridge.
        mRecyclerViewBridge = (RecyclerViewBridge) mMainUpView.getEffectBridge();
        mRecyclerViewBridge.setUpRectResource(R.drawable.test_rectangle);

        mRecyclerView.setOnItemListener(this);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setFocusable(false);


        doHttp();


    }

    private void doHttp() {

        RequestParams params = new RequestParams();
        params.add("login", serverInfo.localAccount().get().toString());
        params.add("org_id", suApplication.getOrgFirstId() + "");
        params.add("count", COUNT);
        HttpClient.get(HttpUrl.CALL_POLICE, params, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showProgressBar();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideProgressBar();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {


            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
         //       Logger.v(responseString);
                ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
                mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                try {
                    JsonNode jsonNode = mapper.readTree(responseString);
                    textView_count.setText("报警总条数" + jsonNode.get("total_count").asText() + "条");
                    List<DangerInfo> mList = mapper.readValue(jsonNode.get("danger_calls"), new TypeReference<List<DangerInfo>>() {
                    });


                    if (mAdapter == null && mList.size() > 0) {
                        mAdapter = new GeneralAdapter(new TvDangerPresenter(mList, CallPliceActivity.this, CallPliceActivity.this));
                        mRecyclerView.setAdapter(mAdapter);
                        mMainUpView.setVisibility(View.VISIBLE);
                        mRecyclerView.requestFocus();
                    }
                    p++;
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }


        });
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    /**
     * 返回
     */
    @Click(R.id.btn_back)
    protected void btnFinish() {
        finish();
    }


    /**
     * 隐藏进度条
     */
    @UiThread
    protected void hideProgressBar() {
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示进度条
     */
    @UiThread
    protected void showProgressBar() {
        progressBar.setVisibility(View.VISIBLE);
    }

    /**
     * 排除 Leanback demo的RecyclerView.
     */
    private boolean isListRowPresenter() {
        GeneralAdapter generalAdapter = (GeneralAdapter) mRecyclerView.getAdapter();
        OpenPresenter openPresenter = generalAdapter.getPresenter();
        return (openPresenter instanceof ListRowPresenter);
    }

    @Override
    public void onItemPreSelected(RecyclerViewTV parent, View itemView, int position) {
        if (!isListRowPresenter()) {
            mRecyclerViewBridge.setUnFocusView(oldView);
        }
    }

    @Override
    public void onItemSelected(RecyclerViewTV parent, View itemView, int position) {
        if (!isListRowPresenter()) {
            mRecyclerViewBridge.setFocusView(itemView, 1.0f);
            oldView = itemView;
        }
    }

    @Override
    public void onReviseFocusFollow(RecyclerViewTV parent, View itemView, int position) {
        if (!isListRowPresenter()) {
            mRecyclerViewBridge.setFocusView(itemView, 1.0f);
            oldView = itemView;
        }
    }

    @Override
    public void adapterstartActivity(Class<?> className, Bundle options) {

    }

    @Override
    public void adapterstartActivityForResult(Class<?> className, Bundle options, int requestcode) {

    }

    int level = 4;
    DangerInfo dangerInfo = null;
    String content;
    List<TextView> mRadioButtons = null;

    @Override
    public void adapterInfotoActiity(Object data, int what) {

        switch (what) {
            case 1:
                if (isLoadMoreFinish) {
                    isLoadMoreFinish = false;
                    RequestParams params = new RequestParams();
                    params.add("login", serverInfo.localAccount().get().toString());
                    params.add("org_id", suApplication.getOrgFirstId() + "");
                    params.add("page", p + "");
                    params.add("count", COUNT);
                    showProgressBar();
                    HttpClient.get(HttpUrl.CALL_POLICE, params, new TextHttpResponseHandler() {
                        @Override
                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                            isLoadMoreFinish = true;
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            hideProgressBar();

                            //mRefreshLayout.onRefreshComplete();
                        }

                        @Override
                        public void onSuccess(int statusCode, Header[] headers, String responseString) {
                            isLoadMoreFinish = true;
                            //Logger.v(responseString);
                            ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
                            mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                            try {
                                JsonNode jsonNode = mapper.readTree(responseString);
                                List<DangerInfo> mList = mapper.readValue(jsonNode.get("danger_calls"), new TypeReference<List<DangerInfo>>() {
                                });
                                p++;
                                if (mAdapter != null && mList.size() > 0) {
                                    mAdapter.addAll(mList);
                                    mMainUpView.setVisibility(View.VISIBLE);
                                    mRecyclerView.requestFocus();
                                } else {
                                    UIUtil.showToast(CallPliceActivity.this, "没有更多了");
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }

                    });
                }
                break;
            case 2:
                dangerInfo = (DangerInfo) data;
                //评价
                //默认优
                level = 4;

                final BaseDialog baseDialog = new BaseDialog(this);
                View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_pinjia, null, false);

                LinearLayout ll_01 = (LinearLayout) dialogView.findViewById(R.id.ll_01);
                LinearLayout ll_02 = (LinearLayout) dialogView.findViewById(R.id.ll_02);
                LinearLayout ll_03 = (LinearLayout) dialogView.findViewById(R.id.ll_03);
                LinearLayout ll_04 = (LinearLayout) dialogView.findViewById(R.id.ll_04);

                final TextView rb01 = (TextView) dialogView.findViewById(R.id.rb_01);
                final TextView rb02 = (TextView) dialogView.findViewById(R.id.rb_02);
                final TextView rb03 = (TextView) dialogView.findViewById(R.id.rb_03);
                final TextView rb04 = (TextView) dialogView.findViewById(R.id.rb_04);

                if (mRadioButtons == null) {
                    mRadioButtons = new ArrayList<>();
                } else {
                    mRadioButtons.clear();
                }

                mRadioButtons.add(rb01);
                mRadioButtons.add(rb02);
                mRadioButtons.add(rb03);
                mRadioButtons.add(rb04);

                ll_01.requestFocus();

                ll_01.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        level = 4;
                        selectPoistion(rb01);
                    }
                });
                ll_02.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        level = 3;
                        selectPoistion(rb02);
                    }
                });
                ll_03.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        level = 2;
                        selectPoistion(rb03);
                    }
                });
                ll_04.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        level = 1;
                        selectPoistion(rb04);
                    }
                });

                final EditText et_content = (EditText) dialogView.findViewById(R.id.et_content);

                LinearLayout tv_cancle = (LinearLayout) dialogView.findViewById(R.id.ll_cancle);
                LinearLayout tv_confirm = (LinearLayout) dialogView.findViewById(R.id.ll_confirm);

                tv_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        baseDialog.dismiss();
                    }
                });

                tv_confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        content = et_content.getText().toString().trim();

                        if (content.length() == 0) {

                            UIUtil.showToast(CallPliceActivity.this, "请填写评价内容");
                            return;

                        }
                        baseDialog.dismiss();
                        showProgressBar();
                        RequestParams params = new RequestParams();

                        params.add("rated_person_id", serverInfo.userId().get() + "");
                        params.add("rated_person_name", serverInfo.userName().get());
                        params.add("detail_info", content);
                        params.add("danger_call_id", dangerInfo.getId() + "");
                        params.add("rated_mark", level + "");

                        HttpClient.post(CallPliceActivity.this, HttpUrl.PUSH_RATED, params, new TextHttpResponseHandler() {
                            @Override
                            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

                            }

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                                hideProgressBar();
                                UIUtil.showToast(CallPliceActivity.this, "评价成功");
                                //如果没有设置，就设置一次
                                if (dangerInfo.getRated_info().size() == 0) {
                                    RatedInfo ratedInfo = new RatedInfo();
                                    ratedInfo.setCreated_at(System.currentTimeMillis() / 1000);
                                    ratedInfo.setDetail_info(content);
                                    ratedInfo.setRated_mark(level);
                                    ArrayList<RatedInfo> ratedInfos = new ArrayList<>();
                                    ratedInfos.add(ratedInfo);
                                    dangerInfo.setRated_info(ratedInfos);
                                    mAdapter.notifyDataSetChanged();
                                }
                            }
                        });


                    }
                });


                baseDialog.setContentView(dialogView);

                baseDialog.show();

                setDialogWindowAttr(baseDialog, this);

                break;
            case 3:
                //查看评价
                dangerInfo = (DangerInfo) data;
                final BaseDialog dialog = new BaseDialog(this);
                View dView = getLayoutInflater().inflate(R.layout.dialog_pinjia_content, null, false);

                final TextView tv_content = (TextView) dView.findViewById(R.id.tv_content);

                LinearLayout tv_confirm_ = (LinearLayout) dView.findViewById(R.id.ll_confirm);
                tv_confirm_.requestFocus();
                TextView tv_time = (TextView) dView.findViewById(R.id.tv_time);

                RadioButton button = (RadioButton) dView.findViewById(R.id.rb_01);

                RatedInfo ratedInfo = dangerInfo.getRated_info().get(0);
                tv_content.setText(ratedInfo.getDetail_info());
                tv_time.setText(DateTool.timestampToStrTime(ratedInfo.getCreated_at() + "", "yyyy-MM-dd HH:mm"));

                switch (ratedInfo.getRated_mark()) {
                    case 1:
                        button.setText("差");
                        break;
                    case 2:
                        button.setText("中");
                        break;
                    case 3:
                        button.setText("良");
                        break;
                    case 4:
                        button.setText("优");
                        break;

                }


                tv_confirm_.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.setContentView(dView);

                dialog.show();

                setDialogWindowAttr(dialog, this);


                break;
        }


    }

    private void selectPoistion(TextView rb) {
        for (TextView tv : mRadioButtons) {
            if (tv == rb) {
                tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_circle_bule));
                tv.setTextColor(getResources().getColor(R.color.white));
            } else {
                tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_circle_white));
                tv.setTextColor(getResources().getColor(R.color.text_black));
            }

        }

    }

    public void setDialogWindowAttr(Dialog dlg, Context ctx) {
        Window window = dlg.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        DisplayMetrics d = ctx.getResources().getDisplayMetrics(); // 获取屏幕宽、高用

        lp.width = (int) (d.widthPixels * 0.8); // 宽度设置为屏幕的0.8
        lp.height = (int) (d.heightPixels * 0.8);
        dlg.getWindow().setAttributes(lp);
    }
}
